using SPI.AgentServer.Models;

namespace SPI.AgentServer.Services.AI;

/// <summary>
/// 模拟的 Qwen 客户端，用于本地测试（无需访问真实大模型）
/// </summary>
public class MockQwenClient : IQwenClient
{
    private readonly ILogger<MockQwenClient> _logger;

    public MockQwenClient(ILogger<MockQwenClient> logger)
    {
        _logger = logger;
    }

    public Task<QwenResponse> ChatCompletionAsync(QwenRequest request, CancellationToken cancellationToken = default)
    {
        var userMessage = request.Messages?.LastOrDefault()?.Content ?? "";
        _logger.LogInformation("Mock Qwen received: {Message}", userMessage);

        var response = new QwenResponse
        {
            Choices = new List<QwenChoice>
            {
                new QwenChoice
                {
                    Message = new QwenMessage
                    {
                        Role = "assistant",
                        Content = GenerateMockResponse(userMessage)
                    }
                }
            }
        };

        return Task.FromResult(response);
    }

    public async Task<ModelResponse> GetStructuredResponseAsync(string prompt, CancellationToken cancellationToken = default)
    {
        _logger.LogInformation("Mock generating response for: {Prompt}", prompt.Substring(0, Math.Min(100, prompt.Length)));
        
        // 模拟延迟
        await Task.Delay(100, cancellationToken);

        // 简单的关键词匹配逻辑
        var promptLower = prompt.ToLower();
        
        // 查找表名
        string tableName = "students"; // 默认表名
        if (promptLower.Contains("学生") || promptLower.Contains("student"))
            tableName = "students";
        else if (promptLower.Contains("课程") || promptLower.Contains("course"))
            tableName = "courses";
        else if (promptLower.Contains("成绩") || promptLower.Contains("grade") || promptLower.Contains("score"))
            tableName = "grades";
        else if (promptLower.Contains("老师") || promptLower.Contains("teacher") || promptLower.Contains("教师"))
            tableName = "teachers";
            
        // 生成SQL
        if (promptLower.Contains("多少") || promptLower.Contains("数量") || promptLower.Contains("count"))
        {
            return new ModelResponse
            {
                Action = new ToolInstruction
                {
                    Tool = "execute_sql",
                    Parameters = new Dictionary<string, object>
                    {
                        ["sql"] = $"SELECT COUNT(*) as total FROM {tableName}",
                        ["databaseName"] = "Test"
                    }
                }
            };
        }
        else if (promptLower.Contains("所有") || promptLower.Contains("查询") || promptLower.Contains("查看"))
        {
            return new ModelResponse
            {
                Action = new ToolInstruction
                {
                    Tool = "execute_sql",
                    Parameters = new Dictionary<string, object>
                    {
                        ["sql"] = $"SELECT * FROM {tableName} LIMIT 100",
                        ["databaseName"] = "Test"
                    }
                }
            };
        }
        else if (promptLower.Contains("结构") || promptLower.Contains("字段") || promptLower.Contains("schema"))
        {
            return new ModelResponse
            {
                Action = new ToolInstruction
                {
                    Tool = "describe_table",
                    Parameters = new Dictionary<string, object>
                    {
                        ["tableName"] = tableName,
                        ["databaseName"] = "Test"
                    }
                }
            };
        }
        else
        {
            return new ModelResponse
            {
                DirectAnswer = $"我理解您想查询关于 {tableName} 的信息，但我需要更具体的指令。您可以尝试：\n" +
                             "- 查询所有记录\n" +
                             "- 统计数量\n" +
                             "- 查看表结构"
            };
        }
    }

    private string GenerateMockResponse(string userMessage)
    {
        // 简单的模拟响应
        if (userMessage.Contains("你好"))
            return "OK";
            
        // 返回模拟的SQL生成响应
        return @"{""action"":{""tool"":""execute_sql"",""parameters"":{""sql"":""SELECT * FROM students"",""databaseName"":""Test""}}}";
    }
}




